﻿using System.Services;
using System.Threading.Tasks;
using Windows.Devices.Sensors;

namespace System.Sensors
{
    public interface IOrientationSensorService : ISensorService<OrientationSensor, OrientationSensorReading>
    {
    }

    [ExportService("OrientationSensorService", "", typeof(IOrientationSensorService), int.MaxValue)]
    public class OrientationSensorService : SensorServiceBase<OrientationSensor, OrientationSensorReading>, IOrientationSensorService
    {
        public OrientationSensorService()
        {
        }

        public override void StartService()
        {
            Sensor = OrientationSensor.GetDefault();
            base.StartService();
        }

        public override void Subscribe()
        {
            if (IsSensorAvailable)
                Sensor.ReadingChanged += Sensor_ReadingChanged;

            base.Subscribe();
        }

        public override void Unsubscribe()
        {
            if (IsSensorAvailable)
                Sensor.ReadingChanged -= Sensor_ReadingChanged;
            base.Unsubscribe();
        }

        void Sensor_ReadingChanged(OrientationSensor sender, OrientationSensorReadingChangedEventArgs args)
        {
            if (EventAggregator != null)
                EventAggregator.Publish<OrientationServiceReadingMessage>(new OrientationServiceReadingMessage(this, args.Reading));
        }

        protected override async Task<OrientationSensorReading> GetSensorData()
        {
            return Sensor.GetCurrentReading();
        }

        public override uint GetMinimumReportInterval()
        {
            return Sensor.MinimumReportInterval;
        }

        public override uint GetReportInterval()
        {
            return Sensor.ReportInterval;
        }

        public override void SetReportInterval(uint value)
        {
            Sensor.ReportInterval = value;
        }
    }


    public class OrientationSensorReadingMessageBase<T> : SensorReadingMessageBase<T>
    {
        public OrientationSensorReadingMessageBase(object sender, T value)
            : base(sender, value)
        {
        }
    }

    public class OrientationServiceReadingMessage : OrientationSensorReadingMessageBase<OrientationSensorReading>
    {
        public OrientationServiceReadingMessage(object sender, OrientationSensorReading value)
            : base(sender, value)
        {
        }
    }

}
